import { Injectable } from '@nestjs/common';
import { v4 } from 'uuid';

@Injectable()
export class BaseService {
  /**
   * 获取一个uuid
   */
  getUuid(): string {
    return v4();
  }

  /**
   * 处理错误
   * @param asyncFunc
   */
  async handleError<T = any>(
    asyncFunc: () => Promise<T>,
  ): Promise<[null, T] | [Error, null]> {
    try {
      const res = await asyncFunc();
      return [null, res];
    } catch (e: any) {
      return [e, null];
    }
  }

  /**
   * 可以用于任何方法的处理错误
   * @param asyncFunc
   */
  async handleError2(asyncFunc: () => any) {
    try {
      const res = await asyncFunc();
      return [null, res];
    } catch (e: any) {
      return [e, null];
    }
  }

  /**
   * 匹配一个
   * @param str
   * @param regExp
   */
  matchOne(str: string, regExp: RegExp) {
    // const reg = /\.[A-z\d]+$/;
    const match = str.match(regExp);
    if (match && match.length === 1) {
      return match[0];
    } else {
      throw new Error(`正则匹配出错:str:${str},regExp:${regExp}`);
    }
  }
}
